<template>
	<div class="padding-container">
		<!-- 搜索栏 -->
		<el-card class="search">
			<!-- 使用el布局 -->
			<el-row>
				<!-- 左侧搜索信息占80% -->
				<el-col :span="20">
					<div class="search_grop">
						<el-input placeholder="请输入内容" prefix-icon="el-icon-search" v-model="inputObject.inputText"
							:id="inputObject.search_id">
						</el-input>

					</div>
				</el-col>
				<!-- 左侧搜索栏按钮占20% -->
				<el-col :span="4">
					<el-col :span="12">
						<div>
							<el-button type="primary" v-waves plain size="medium">按钮</el-button>
						</div>
					</el-col>
					<el-col :span="12">
						<div>
							<el-button type="success" plain size="medium">按钮</el-button>
						</div>

					</el-col>
				</el-col>
			</el-row>
		</el-card>
		<!-- 地图主体 -->
		<el-card class="tables">
			<div class="flex space-between">
				<div id="container"></div>
				<div class="addInformation">
					<el-tag type="success">景区坐标</el-tag>
					<span>经度:<el-input placeholder="经度" v-model="scenic.scenicLongitude" clearable>
						</el-input></span>
					<span>纬度:<el-input placeholder="纬度" v-model="scenic.scenicLatitude " clearable>
						</el-input></span>
					<el-button class="orientation" type="primary" icon="el-icon-location-outline">定位</el-button>
					<div class="spotAdd">
						<el-tag type="success">景点添加</el-tag>
						<span>景点名称:<el-input placeholder="名称" v-model="spotInformation.attractionsName" clearable>
							</el-input></span>
						<div class="positionAdd">
							<span>经度:<el-input placeholder="经度" v-model="spotInformation.longitude" clearable>
								</el-input></span>
							<span>纬度:<el-input placeholder="纬度" v-model="spotInformation.latitude " clearable>
								</el-input></span>
							<span>状态
								<el-select v-model="spotInformation.attractionsState" clearable placeholder="请选择">
									<el-option v-for="item in statusOption" :key="item.value" :label="item.label"
										:value="item.value">
									</el-option>
								</el-select></span>
						</div>
						<div>
							<span>介绍:</span>
							<el-input type="textarea" placeholder="请输入内容"
								v-model="spotInformation.attractionsIntroduction" maxlength="40" show-word-limit>
							</el-input>
						</div>
						<div class="phoneAdd">
							<span>上传景点图片:</span>
							<div class="flex space-between">
								<el-upload action="/api/attractions/insert" :data="this.spotInformation"
									list-type="picture-card" :on-preview="handlePictureCardPreview"
									:on-remove="handleRemove" :auto-upload="false" :limit="1" ref="upload">
									<i class="el-icon-plus"></i>
								</el-upload>
								<el-dialog :visible.sync="dialogVisible">
									<img width="100%" :src="dialogImageUrl" alt="">
								</el-dialog>
								<div>
									<div class="businessHours">
										<div>营业时间:</div>
										<el-time-picker is-range v-model="businessHours" range-separator="至"
											start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围"
											value-format="HH:mm:ss">
										</el-time-picker>
									</div>
									<div class="SubmitInfor flex space-between">
										<el-button type="primary" @click="submitInfor" v-if="buttonSwitch">添加景点<i
												class="el-icon-upload el-icon--right"></i></el-button>
										<el-button type="primary" @click="modifyAttractions" v-if="!buttonSwitch"><i
												class="el-icon-edit el-icon--right"></i>确认修改</el-button>
										<el-button type="primary" @click="deleteAttractions"
											v-if="!buttonSwitch && this.spotInformation.attractionsState==1">删除景点<i
												class="el-icon-delete el-icon--right"></i></el-button>
										<el-button type="primary" @click="recoverAttractions"
											v-if="this.spotInformation.attractionsState==2">恢复景点<i
												class="el-icon-set-up el-icon--right"></i></el-button>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</el-card>
	</div>
</template>

<script>
	import waves from "@/directives/waves/index.js"
	import ElDrag from "@/directives/ElDrag/index.js"
	import MdInput from "@/components/MDInput"
	import {
		addInsert,
		selectAttractionsById,
		modifyAttractions,
		deleteAttractions,
		recoverAttractions
	} from "@/api/attractions"
	//引入高德地图
	import AMapLoader from '@amap/amap-jsapi-loader'
	//配置安全密钥
	window._AMapSecurityConfig = {
		securityJsCode: '9dcc44217689d5f8eecc906fef15841a' //*  安全密钥
	}
	export default {
		directives: {
			waves,
			ElDrag
		},
		components: {
			MdInput
		},
		data() {
			return {
				buttonSwitch: true, //判断添加，删除，修改控制器
				dialogImageUrl: '', //放大图片的地址
				businessHours: [], //营业时间
				currentMarker: '', //存储当前标记对象
				statusOption: [{
					value: 1,
					label: '营业'
				}, {
					value: 2,
					label: '歇业'
				}, ], //景点状态选择
				dialogVisible: false,
				scenic: {
					scenicLongitude: '', //景区经度
					scenicLatitude: '', //景区纬度
				},

				inputObject: {
					search_id: 'searchId',
					inputText: ''
				},
				map: null, //地图实例
				autoOptions: {
					input: ''
				},
				auto: null,
				placeSearch: null,
				//景点信息
				spotInformation: {
					id: '', //景点id
					latitude: '', //纬度
					longitude: '', //经度
					attractionsName: '',
					iconPath: '', // 标记图标的路径
					attractionsIntroduction: '',
					attractionsPicture: '',
					attractionsState: '', //景点状态
					attractionsStart: '', //开馆时间
					attractionsEnd: ''
				},
				//存放先前存放的标记
				listTemporarily: '', //暂存集合
			}
		},
		created() {
			this.$on('share_id', value => {
				this.autoOptions.input = value.search_id
				// console.log(value)
			})
		},
		mounted() {

			this.initMap()
			this.sendId()

		},
		methods: {

			handleUploadSuccess(response, file) {
				console.log("Uploaded successfully:", file.name);
			},
			handleRemove(file, fileList) {
				console.log(file, fileList);
			},
			handlePictureCardPreview(file) {
				this.dialogImageUrl = file.url;
				this.dialogVisible = true;

			},
			sendId() {
				this.$emit('share_id', this.inputObject)
				// console.log(this.inputObject)
			},
			initMap() {
				AMapLoader.load({
					key: "e4e8bf788dae6eaef0be064e1e6c4b93", // 申请好的Web端开发者Key，首次调用 load 时必填
					version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
					plugins: ['AMap.ToolBar', 'AMap.Scale', 'AMap.HawkEye', 'AMap.MapType',
						'AMap.Geolocation', 'AMap.AutoComplete', 'AMap.PlaceSearch', 'AMap.Geocoder'
					], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
				}).then((AMap) => {
					this.map = new AMap.Map("container", { //设置地图容器id
						viewMode: "3D", //是否为3D地图模式
						zoom: 15, //初始化地图级别
						center: [116.397128, 39.916527], //初始化地图中心点位置
					})
					const map = this.map;
					this.map.addControl(new AMap.Scale())
					this.map.addControl(new AMap.ToolBar())
					this.map.addControl(new AMap.HawkEye())
					this.map.addControl(new AMap.MapType())
					this.map.addControl(new AMap.Geolocation())
					this.auto = new AMap.AutoComplete(this.autoOptions)
					this.placeSearch = new AMap.PlaceSearch({
						map: this.map
					}) //构造地点查询类
					this.auto.on('select', this.select)
					//点击地图事件
					this.map.on('click', e => {
						// let lng = e.lnglat.lng
						// let lat = e.lnglat.lat
						this.getLngLatService(e.lnglat)
					})

					const spotInformation = this.spotInformation
					const doBusiness = this.businessHours
					this.selectAttractions()
				}).catch(e => {
					console.log(e);
				});

			},
			select(e) {
				this.placeSearch.setCity(e.poi.adcode)
				this.placeSearch.search(e.poi.name) //关键字查询查询
			},
			//设置标记点
			MarkerDataFromDB() {
				this.map.clearMap();
				const spotInformation = this.spotInformation
				const doBusiness = this.businessHours
				const map = this.map
				this.listTemporarily.forEach(function(data) {
					var blueIcon = new AMap.Icon({
						size: new AMap.Size(20, 30), // 图标尺寸
						image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png', // 图标的 URL
						imageSize: new AMap.Size(20, 30) // 图标显示大小
					});
					var redIcon = new AMap.Icon({
						size: new AMap.Size(20, 30), // 图标尺寸
						image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png', // 图标的 URL
						imageSize: new AMap.Size(20, 30) // 图标显示大小
					})


					var marker = new AMap.Marker({
						position: [data.longitude, data.latitude],
						map: map,
					});
					if (data.attractionsState == 1) {
						marker.setIcon(blueIcon)
					} else if (data.attractionsState == 2) {
						marker.setIcon(redIcon)
					}
					marker.on('click', function() {
						console.log('spotInformationspotInformation', spotInformation),
							spotInformation.id = data.id,
							spotInformation.latitude = data.latitude, //纬度
							spotInformation.longitude = data.longitude, //经度
							spotInformation.attractionsName = data.attractionsName,
							spotInformation.attractionsIntroduction = data
							.attractionsIntroduction,
							spotInformation.attractionsPicture = data.attractionsPicture,
							spotInformation.attractionsState = data.attractionsState, //景点状态
							spotInformation.attractionsStart = data.attractionsStart, //开馆时间
							spotInformation.attractionsEnd = data.attractionsEnd,
							doBusiness.splice(0, doBusiness.length),
							doBusiness.splice(0, 0, data.attractionsStart, data.attractionsEnd)

						// 这里可以根据需要返回更多数据
					});
				})
			},
			getLngLatService(lnglat) {
				let geocoder = new AMap.Geocoder({
					city: '全国' // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
				})
				if (this.currentMarker) {
					this.map.remove(this.currentMarker);
				}
				//添加点标记
				let marker1 = new AMap.Marker({
					position: new AMap.LngLat(lnglat.lng, lnglat.lat),
					title: 'New Marker'
				})
				this.map.add(marker1)
				//经度，纬度
				console.log("点坐标", lnglat.lng, lnglat.lat)
				this.currentMarker = marker1;
				this.spotInformation.id = '',
					this.spotInformation.longitude = lnglat.lng,
					this.spotInformation.latitude = lnglat.lat,
					this.spotInformation.attractionsName = '',
					this.spotInformation.attractionsIntroduction = ''
				this.spotInformation.attractionsPicture = '',
					this.spotInformation.attractionsState = '', //景点状态
					this.spotInformation.attractionsStart = '', //开馆时间
					this.spotInformation.attractionsEnd = '',
					this.businessHours.splice(0, this.businessHours.length),
					this.buttonSwitch = true
			},
			//添加景点
			submitInfor() {
				this.spotInformation.attractionsStart = this.businessHours[0]
				this.spotInformation.attractionsEnd = this.businessHours[1]
				this.$refs.upload.submit()
				console.log("景点信息：", this.businessHours)
				// addInsert(this.spotInformation).then(res => {
				// 	this.selectAttractions()
				// 	this.$message({
				// 		message: res.data,
				// 		type: 'success'
				// 	});
				// 	console.log(res)
				// })
			},
			//获取景点列表
			selectAttractions() {
				selectAttractionsById(0).then(res => {
					this.deleSpotInformation()
					this.listTemporarily = res.data
					this.MarkerDataFromDB()
					console.log("景点列表", this.listTemporarily)
				})
			},
			//修改景点信息
			modifyAttractions() {
				modifyAttractions(this.spotInformation).then(res => {
					this.selectAttractions()
					this.$message({
						message: res.data,
						type: 'success'
					});
					console.log('修改景点信息', res)

				})
			},
			//逻辑删除景点
			deleteAttractions() {
				deleteAttractions(this.spotInformation.id).then(res => {
					this.selectAttractions()
					this.$message({
						message: res.data,
						type: 'success'
					});
					console.log('删除景点', res)

				})
			},
			//删除spotInformation属性
			deleSpotInformation() {
				this.spotInformation.id = '',
					this.spotInformation.longitude = '',
					this.spotInformation.latitude = '',
					this.spotInformation.attractionsName = '',
					this.spotInformation.attractionsIntroduction = ''
				this.spotInformation.attractionsPicture = '',
					this.spotInformation.attractionsState = '', //景点状态
					this.spotInformation.attractionsStart = '', //开馆时间
					this.spotInformation.attractionsEnd = '',
					this.businessHours.splice(0, this.businessHours.length),
					this.buttonSwitch = true
			},
			//恢复已删除的景点
			recoverAttractions() {
				recoverAttractions(this.spotInformation.id).then(res => {
					this.selectAttractions()
					this.$message({
						message: res.data,
						type: 'success'
					});
					console.log('恢复景点', res)

				})
			}
		},
		watch: {
			'spotInformation.id': function(newValue, oldValue) {
				if (newValue != '') {
					this.buttonSwitch = false
				}
				console.log(`myProperty changed from ${oldValue} to ${newValue}`);
			}
		},
	}
</script>

<style scoped>
	#container {
		width: 500px;
		height: 300px;
	}

	.addInformation {
		width: 500px;
		height: 300px;
	}

	/deep/.el-input {
		width: 120px;
		height: 40px;
	}

	.SubmitInfor {
		margin-top: 40px;
		margin-left: 20px;
		color: red;
	}

	.businessHours {
		margin-left: 20px;

	}

	.el-date-editor.el-range-editor.el-input__inner.el-date-editor--timerange {
		width: 300px;
	}

	.orientation {
		margin-left: 25px;
	}

	/deep/.el-select .el-input__inner {
		width: 150px;
		padding-left: 35px;
	}

	.spotAdd,
	.positionAdd,
	.phoneAdd {
		margin-top: 10px;
	}
</style>